import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../form_builder.dart';

class RadioItem<T> {
  final String label;
  final T data;

  RadioItem({
    required this.label,
    required this.data,
  });
}

class RadioGroupFormField<T> extends BaseFormField {
  final String name;
  final String? label;
  final String? Function(dynamic value)? validator;
  final List<RadioItem<T>> items;
  final void Function(T value)? onChange;

  RadioGroupFormField({
    required this.name,
    required this.items,
    this.label,
    this.validator,
    this.onChange,
  }) : super(name: name, label: label, validator: validator);

  @override
  BaseFormFieldState createState() {
    return _RadioGroupFormFieldState<T>();
  }
}

class _RadioGroupFormFieldState<T> extends BaseFormFieldState {
  @override
  Widget build(BuildContext context) {
    List<Widget> radios = [];
    for (RadioItem<T> item in (widget as RadioGroupFormField<T>).items) {
      Radio<T> radio = Radio<T>(
        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
        onChanged: (value) {
          setState(() {
            this.value = value ?? null as T;
          });
          var change = (widget as RadioGroupFormField<T>).onChange;
          if (change != null) {
            change(this.value);
          }
        },
        value: item.data,
        groupValue: value,
      );
      radios.add(radio);
      radios.add(
        Text(
          "${item.label}：",
          style: TextStyle(color: Color(0xff666666), fontSize: 24.sp),
        ),
      );
    }
    return labelWrapper(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[...radios],
      ),
    );
  }

  T get initialValue {
    if (initValueMap != null && initValueMap!.containsKey(name)) {
      return initValueMap![name];
    }
    return null as T;
  }

  @override
  void initState() {
    super.initState();
  }

  void initFormManagement() {
    super.initFormManagement();
    this.value = initialValue;
  }

  void dispose() {
    super.dispose();
  }
}
